package com.miplus.ccrm.core.api.fastgpt;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.miplus.ccrm.common.ServiceException;
import com.miplus.ccrm.core.api.fastgpt.model.BlockResponse;
import com.miplus.ccrm.core.api.fastgpt.model.ChatRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * FastGPT API服务类
 */
@Service
@Slf4j
public class FastGptService {

    private static final String FASTGPT_URL = "http://47.92.159.23:3000/api/v1/chat/completions";


    /**
     * 发送阻塞式聊天请求
     *
     * @param request
     * @return
     */
    public static BlockResponse sendChatRequest(ChatRequest request, String authKey) {
        log.info("请求FastGPT参数: {}", JSONUtil.toJsonStr(request));
        //获取请求头
        String authHeader = authKey;
        if (request == null) {
            throw new RuntimeException("参数为空");
        }
        try {
            HttpResponse response = HttpRequest.post(FASTGPT_URL)
                    .header("Authorization", "Bearer " + authHeader)
                    .header("Content-Type", "application/json")
                    .body(JSONUtil.toJsonStr(request))
                    .timeout(3000000).execute();
            if (response.isOk()) {
                String result = response.body();
                log.info("FastGPT响应成功: {}", result);
                // 解析FastGPT原始响应
                BlockResponse blockResponse = JSONUtil.toBean(result, BlockResponse.class);
                // 提取 content 中的 JSON 字符串
                String contentWithCodeBlock = blockResponse.getChoices().get(0).getMessage().getContent();
                String cleanedJson = cleanCodeBlock(contentWithCodeBlock); // 调用清理Json代码块
                //log.info("返回结构化数据: {}", blockResponse.getChoices().get(0).getMessage().getContent());
                log.info("返回结构化数据: {}", cleanedJson);
                blockResponse.getChoices().get(0).getMessage().setContent(cleanedJson);
//                JSONObject jsonObject = JSONUtil.parseObj(contentWithCodeBlock);
                // blockResponse.setAiresponse(jsonObject);
                return blockResponse;
            } else {
                log.error("FastGPT响应失败，状态码: {}, 响应: {}", response.getStatus(), response.body());
                throw new RuntimeException("FastGPT API请求失败: " + response.getStatus());
            }
        } catch (Exception e) {
            log.error("FastGPT请求超时或发生异常: ", e);
            throw new RuntimeException("FastGPT API请求超时或发生异常: " + e.getMessage());
        }
    }

    /**
     * 清楚代码块
     *
     * @param input
     * @return
     */
    private static String cleanCodeBlock(String input) {
        // 正则表达式去除 ```json 和 ```（支持换行）
        return input.replaceAll("^```json\\s*|\\s*```$", "");
    }
}
